import React from 'react';
import ReactDOM from 'react-dom';
import { Toast, Button, WingBlank, Icon, Result, WhiteSpace, List ,InputItem} from 'antd-mobile';
import { Setting } from './components/Setting';
import Translate from './components/Translate';
import Header from './components/Header';
import Footer from './components/Footer';
import GetValiCode from './components/FormItem-GetValiCode';
import { createForm } from 'rc-form';
import './forget.css'
import 'whatwg-fetch'


function convert_FormData_to_json (formData) {
  var objData = {};

  for (var entry of formData.entries()){
      objData[entry[0]] = entry[1];
  }
  return JSON.stringify(objData);
};

function loadingToast(message) {
  Toast.loading(message, 60)
}


class App extends React.Component{

  constructor(){
    super();
    this.state = {
      success: false, // 第一步是否成功
      form: {
        mobile: {
          valid: /(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/
        },
        code: {
          valid: false
        },
        password: {
          valid: false
        },
        password_confirmation: {
          valid: false
        }
      },
      storage1: { // 存储第一步的手机号与密码
        mobile: '',
        code: ''
      }
    }
  }

  valiClickHandle = (phoneNum) => {
    fetch( Setting.BaseUrl + "password-vcode", {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({mobile: phoneNum})
    }).then((resp) => {
      return resp.json();
    }).then((json) => {
      console.log('valiClickHandle')
      if (json.success) {
        console.log('验证码已发送')
      } else {
        console.error('验证码发送失败');
      }
    })
    console.log('请求验证码')
  }

  fetchValiPhone = () => {
    console.log('验证手机号与验证码')
    let validData = true;
    for( let name in this.state.form){
      let text = this.props.form.getFieldValue(name) || '' ,
          reg = this.state.form[name].valid;
      switch ( name )
      {
        case 'mobile':
          if( text.length == 0 ){
            Toast.fail( '手机号不能为空', 2 );
            validData = false;
          } else if (!reg.test(text)) {
            Toast.fail( '请输入正确的手机号', 2 );
            validData = false;
          }
          break;
        case 'code':
          if( text.length == 0 ){
            Toast.fail( '验证码不能为空', 2 );
            validData = false;
          }
          break;
      };
    };

    if( !validData )return false;

    let form = document.getElementById('valiPhone');
    // console.log(convert_FormData_to_json(new FormData(form)));
    loadingToast()
    fetch( Setting.BaseUrl + "check-vcode" , {
      method: 'POST',
      headers: {
          // 'Content-Type': 'application/json'
      },
      body: new FormData(form)
    }).then((resp) => {
      return resp.json();
    }).then((json) => {
      Toast.hide()
      if (json.success) {
        Toast.info('验证成功', 2, () => {
          this.setState({success: true, storage1: JSON.parse(convert_FormData_to_json(new FormData(form)))});
        })
      } else {
        Toast.fail( json.error, 2 );
      };
    })

  }

  fetchResetPsw = () => {
    console.log('请求重置密码')
    let validData = true;
    for( let name in this.state.form){
      let text = this.props.form.getFieldValue(name) || '' ,
          reg = this.state.form[name].valid;
      switch ( name )
      {
        case 'password':
          if( text.length == 0 ){
            Toast.fail( '密码不能为空', 2 );
            validData = false;
          } else if (text != this.props.form.getFieldValue('password_confirmation')) {
            Toast.fail( '两次输入的密码不一致', 2 );
            validData = false;
          }
          break;
        case 'password_confirmation':
          if( text.length == 0 ){
            Toast.fail( '密码不能为空', 2 );
            validData = false;
          } else if (text != this.props.form.getFieldValue('password')) {
            Toast.fail( '两次输入的密码不一致', 2 );
            validData = false;
          }
          break;
      };
    };

    if( !validData )return false;

    let form = document.getElementById('resetPsw');
    let formData = new FormData(form);
    // let resetJsonO = JSON.parse(convert_FormData_to_json(new FormData(form)));
    // console.log(this.props.form.getFieldsValue());
    formData.append('mobile', this.state.storage1.mobile);
    formData.append('code', this.state.storage1.code);

    fetch( Setting.BaseUrl + "password-new" , {
      method: 'POST',
      headers: {
          // 'Content-Type': 'application/json'
      },
      body: formData
    }).then((resp) => {
      return resp.json();
    }).then((json) => {
      Toast.hide()
      if (json.success) {
        Toast.info('重置成功', 2, () => {
          window.location.href = "/";
        })
      } else {
        Toast.fail( json.error, 2 );
      };
    })

  }

  render() {
    const { getFieldProps } = this.props.form;
    const { success } = this.state;
    return (
          <div className="container enroll-container" id="container">
          	<Header title="忘记密码" leftContent="" />
            {
              !success ? <div className="padding-hor">
                <form id="valiPhone">
                  <GetValiCode
                    form={this.props.form}
                    valiClick={this.valiClickHandle}/>
                </form>
                <WhiteSpace size="xl" />
                <Button className="btn" type="primary" onClick={this.fetchValiPhone}>下一步</Button>
              </div> : <div className="padding-hor">
                <form id="resetPsw">
                  <List>
                    <InputItem
                      placeholder="新的密码"
                      type="password"
                      {...getFieldProps('password')}
                      name="password"
                    ></InputItem>
                  </List>
                  <WhiteSpace />

                  <List>
                    <InputItem
                      placeholder="重复新的密码"
                      type="password"
                      {...getFieldProps('password_confirmation')}
                      name="password_confirmation"
                    ></InputItem>
                  </List>

                </form>
                <WhiteSpace size="xl" />
                <Button className="btn" type="primary" onClick={this.fetchResetPsw}>完成</Button>
              </div>
            }

          </div>
    );
  }
}
export default App = createForm()(App)
ReactDOM.render(<App />, document.getElementById('example'));
